package com.mis.pos.controller;

import com.mis.pos.common.utils.ApiResponse;
import com.mis.pos.common.utils.PageUtil;
import com.mis.pos.dto.*;
import com.mis.pos.entity.InventoryEntity;
import com.mis.pos.entity.SaleEntity;
import com.mis.pos.form.InventoryForm;
import com.mis.pos.form.ItemSearchForm;
import com.mis.pos.service.InventoryService;
import com.mis.pos.service.ItemService;
import com.mis.pos.service.SaleService;
import com.mis.pos.service.dsl.InventorySearchService;
import com.mis.pos.service.dsl.ItemSearchService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description 库存管理控制类
 * @Author yuxiang
 * @CreatedDate 2019/11/25 11:54
 */
@RestController
@RequestMapping("/inventory")
public class InventoryController {

    Logger logger = LoggerFactory.getLogger(InventoryController.class);

    @Autowired
    private InventorySearchService inventorySearchService;
    @Autowired
    private ItemService itemService;
    @Autowired
    private InventoryService inventoryService;
    @Autowired
    private SaleService saleService;
    @Autowired
    private ItemSearchService itemSearchService;


    @PostMapping("searchInventory")
    public ApiResponse searchInventory(@RequestBody ItemSearchForm searchForm,
                                       @RequestParam(value = "pageNumber",defaultValue = "1") Integer pageNumber,
                                       @RequestParam(value = "pageSize",defaultValue = "10")Integer pageSize){
        ApiResponse apiResponse = new ApiResponse();
        List<InventoryDTO> dtos = new ArrayList<>();
        Integer maxCount = 0;

        try{

            Map map = inventorySearchService.searchInventoryByItemForm(searchForm,(pageNumber-1)*pageSize,pageSize);

            dtos = (List<InventoryDTO>) map.get("dtos");
            maxCount = (Integer) map.get("count");

        }catch (Exception e){
            e.printStackTrace();
            logger.error("服务器出现错误,无法查询库存信息");
            return new ApiResponse(-1,"服务器出现错误,无法查询库存信息");
        }
        return PageUtil.pageManual(dtos,pageNumber,pageSize,maxCount);
    }


    /**
     * 商品进货
     * @param form
     * @return
     */
    @PostMapping("/addInventory")
    public ApiResponse addInventory(@RequestBody InventoryForm form){

        ApiResponse response =new ApiResponse();
        List itemNumberDtos = new ArrayList();
        try {
            //1.增加库存
//            List<InventoryEntity> inventoryEntities = new ArrayList<>();
            List<AddItemDTO> addItemDTOS = form.getDtos();
            for (AddItemDTO dto :
                    addItemDTOS) {
                if (itemService.findOneById(dto.getItemId())==null){
                    return new ApiResponse(-1,"商品id不正确！");
                }
                Long number = Long.valueOf(dto.getNumber());
                //改变库存
                inventoryService.addInventory(dto.getItemId(),number);
                ItemNumberDTO temp  = new ItemNumberDTO(dto.getItemId(),dto.getItemName(),number);
                itemNumberDtos.add(temp);
            }

            //2.添加订单信息
            SaleEntity saleEntity = new SaleEntity(form.getTotal(),"进货单",0);
            saleService.save(saleEntity);
            //3.订单和商品关联
            //商品ids
            if (saleService.save(saleEntity)==0){
                saleService.saveSaleItem(itemNumberDtos,saleEntity.getId());
            }else {
                return new ApiResponse(-1,"服务器错误，生成订单失败");
            }

            //返回response
            response.setMsg("进货成功");

        }catch (Exception e){
            logger.error("进货失败");
            e.printStackTrace();
            return new ApiResponse(-1,"商品失败！");
        }
        return response;
    }

    /**
     * 获取供应商
     * @return
     */
    @GetMapping("getSupply")
    public ApiResponse getAllSupplies(){
        ApiResponse response = new ApiResponse();
        try {
            List<String> brands = itemService.getAllBrands();
            response.setObj(brands);
            response.setMsg("获取品牌成功");
        }catch (Exception e){
            e.printStackTrace();
            return new ApiResponse(-1,"服务器出现错误");
        }
        return response;
    }


    /**
     * 商品查询
     * @param brand 商标
     * @param pageNumber 页数
     * @param pageSize 一页多少条
     * @return
     */
    /**
     * 商品查询
     * @param searchForm 查询表单
     * @param pageNumber 页数
     * @param pageSize 一页多少条
     * @return
     */
    @PostMapping("/searchItem")
    public ApiResponse searchItem(@RequestBody ItemSearchForm searchForm,
                                  @RequestParam(value = "pageNumber",defaultValue = "1")Integer pageNumber,
                                  @RequestParam(value = "pageSize",defaultValue = "10")Integer pageSize){
        List<ItemDTO> dtos = new ArrayList<>();
        List<AddItemDTO> addItemDTOS = new ArrayList<>();
        Map map  = new HashMap();
        Integer count  = 0;
        try {
            map = itemSearchService.searchByItemForm(searchForm, (pageNumber-1)*pageSize, pageSize);
            dtos = (List<ItemDTO>) map.get("dtos");
            //返回的数据
            for (ItemDTO dto:
                 dtos) {
                AddItemDTO temp = new AddItemDTO(dto.getId(),dto.getItemName(),0,dto.getPrice());
                addItemDTOS.add(temp);
            }
            count = Math.toIntExact((Long) map.get("count"));
        }catch (Exception e){
            logger.info("服务器出异常");
            e.printStackTrace();
            return new ApiResponse(-1,"服务器出异常");
        }

        return PageUtil.pageManual(addItemDTOS,pageNumber,pageSize,count);
    }
}
